#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import logging
import optparse
import sys

from oriolus.gaffer.gaffer import GafferFactory

# cli.py install agami-1.0.0.0
# cli.py remove agami-1.0.0.0
# cli.py install_local c:\\agami
# cli.py get
# cli.py upgrade

def exit(parser):
    parser.print_help()
    parser.destroy()
    sys.exit(0)
    
def check_args_count(args, number, parser):
    if len(args) != number:     
        exit(parser)    

def run():
    list = ["install", "remove", "install_local", "update_list", "upgrade", "install_configuration", "prefetch_configuration"]
    usage = """usage: cli.py command [args]
    command:
        install [names] - install packets with specified names
        remove [names] - remove packets with specified names        
        update_list - update index packet on local drive
        upgrade [names] - upgrade packets in list or all if there any
        install_configuration [names] - installs specified configuration
        prefetch_configuration [names] - perform a dry-run with install_configuration"""
    
    parser = optparse.OptionParser(usage=usage, version = "OriolusGaffer 0.1.0")
    parser.add_option("-l", dest = "loglevel", action="count", help = "set logging level, the count of option defines logging level (-l: DEBUG, -ll: INFO, -lll: WARNING, -llll: ERROR, -lllll: CRITICAL)")
    parser.add_option("--log", dest = "logfilename", default = "./gaffer.log.txt", help = "set log file name [default: %default]")
    parser.add_option("-c", "--config", dest = "config", help = "Path for gaffer configuration file")
    parser.add_option("-f", "--from", dest = "fromlocal", help = "Install packet from local folder")
    parser.add_option("-b", "--base_path", dest="base_path", help = "Base installation path")
    parser.add_option("-v", "--no-verification", dest = "no_verification", action = "store_false", default = True, help = "disable packet verification [default: %default]")
    
    (options, args) = parser.parse_args()
    
    if len(args) == 0:
        exit(parser)    
    
    flag = False
    for each in args:
        if (not flag) and (each in list):
            flag = True
        elif (flag) and (each in list):
            exit(parser)

    loglevel = 0
    if options.loglevel:
        if options.loglevel > 5:
            options.loglevel = 5
        loglevel = options.loglevel * 10
        logging.basicConfig(level = loglevel, filename = options.logfilename, format = "%(asctime)-15s [%(thread)d] %(levelname)-5s %(name)s - %(message)s", )
    else:
        logging.basicConfig(level = logging.INFO, format = "[%(levelname)s] %(message)s", )
        
    fromlocal = None
    if options.fromlocal:
        fromlocal = options.fromlocal

    command = args[0]

    factory = GafferFactory()
    if options.config:
        gaffer = factory.get_gaffer(config_path = options.config, fromlocal = fromlocal, use_virtual_docker = (command == 'prefetch_configuration'))
    else:
        gaffer = factory.get_gaffer(fromlocal = fromlocal, use_virtual_docker = (command == 'prefetch_configuration'))    
    
    if command == "install":        
        gaffer.install(args[1:], base_path = options.base_path)            
    if command == "remove":         
        gaffer.remove(args[1:])    
    if command == "update_list":
        check_args_count(args, 1)
        gaffer.update_list()
    if command == "upgrade":
        check_args_count(args, 1)
        packets_for_upgrade = args[1:]
        if packets_for_upgrade in [None, [], ""]:
            packets_for_upgrade = []
            
        gaffer.upgrade(packets_for_upgrade, base_path = options.base_path)
    if command == "install_configuration":
        #check_args_count(args, 1)
        print args
        configuration = args[1:]
        if configuration in [None, [], ""]:
            configuration = []
           
        print "Installing configuration " + str(configuration)
        gaffer.install_configuration(configuration, options.base_path)

    if command == 'prefetch_configuration':
        print args
        configuration = args[1:]
        if configuration in [None, [], ""]:
            configuration = []
        print "Prefetching configuration " + str(configuration)
        gaffer.install_configuration(configuration, options.base_path)
        
if __name__ == "__main__":
    run()
